<template>
  <div class="auth-container">
    <div v-if="isLoggedIn" class="user-dropdown">
      <button class="auth-button" @click="toggleDropdown">
        欢迎, {{ username }}
      </button>
      <div v-if="showDropdown" class="dropdown-menu">
        <div class="dropdown-item" @click="handleLogout">退出登录</div>
      </div>
    </div>
    <button v-else class="auth-button" @click="showAuthModal = true">
      登录/注册
    </button>
    
    <AuthModal 
      v-model:visible="showAuthModal"
      @login-success="handleLoginSuccess"
      @register-success="handleRegisterSuccess"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import AuthModal from './AuthModal.vue';
import { getToken, logout } from '../api/auth';

const showAuthModal = ref(false);
const isLoggedIn = ref(false);
const username = ref('');
const showDropdown = ref(false);

// 检查是否已登录
onMounted(() => {
  const token = getToken();
  if (token) {
    isLoggedIn.value = true;
    // 这里简单处理，实际应该从token解析用户信息或从本地存储获取
    username.value = localStorage.getItem('username') || '用户';
  }
});

const handleLoginSuccess = (userData) => {
  isLoggedIn.value = true;
  username.value = userData.username;
  localStorage.setItem('username', userData.username);
};

const handleRegisterSuccess = (userData) => {
  isLoggedIn.value = true;
  username.value = userData.username;
  localStorage.setItem('username', userData.username);
};

const toggleDropdown = () => {
  showDropdown.value = !showDropdown.value;
};

const handleLogout = async () => {
  try {
    const result = await logout();
    if (result.success) {
      isLoggedIn.value = false;
      username.value = '';
      localStorage.removeItem('username');
      showDropdown.value = false;
      // 可以添加提示信息
      console.log('退出登录成功');
    } else {
      console.error('退出登录失败:', result.message);
    }
  } catch (error) {
    console.error('退出登录出错:', error);
  }
};

// 点击外部区域关闭下拉菜单
const closeDropdown = (e) => {
  if (showDropdown.value && !e.target.closest('.user-dropdown')) {
    showDropdown.value = false;
  }
};

// 添加全局点击事件监听
onMounted(() => {
  document.addEventListener('click', closeDropdown);
});
</script>

<style scoped>
.auth-container {
  display: inline-block;
  position: relative;
}

.auth-button {
  background-color: #00c25e;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.auth-button:hover {
  background-color: #00ae53;
}

.user-dropdown {
  position: relative;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  width: 120px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  margin-top: 5px;
  z-index: 100;
}

.dropdown-item {
  padding: 10px 15px;
  cursor: pointer;
  color: #333;
  font-size: 14px;
  transition: background-color 0.2s;
}

.dropdown-item:hover {
  background-color: #f5f5f5;
  color: #00c25e;
}
</style> 